package wypozyczalnia.service;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Hibernate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import wypozyczalnia.dao.UserDao;
import wypozyczalnia.domain.User;

@Service("userService")
@Transactional
public class UserService implements UserDetailsService {

	@Autowired
	private UserDao userDao;

	public void create(User user) {
		userDao.save(user);

	}

	public void deleteByUsername(String username) {
		User user = userDao.getById(username);
		if (user != null) {
			userDao.delete(user);
		}
	}

	public List<User> getAllUsers() {
		return userDao.getAll();
	}

	public User getUserByUsername(String username) {
		User user = userDao.getById(username);
		Hibernate.initialize(user.getAuthorities());
		return user;
	}

	public void update(User user) {
		userDao.saveOrUpdate(user);
	}

	public UserDetails getUserDetails(User user) {
		String roleName = "ROLE_USER";
		GrantedAuthorityImpl g = new GrantedAuthorityImpl(roleName);
		List<GrantedAuthority> list = new ArrayList<GrantedAuthority>();
		list.add(g);
		return new org.springframework.security.core.userdetails.User(
				user.getUsername(), user.getPassword(), user.isEnabled(), true,
				true, true, list);
	}

	@Override
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException, DataAccessException {
		
		User user = userDao.getById(username);

		return user;

	}

	public List<User> getUserSearch(String term, int LIMIT) {
		return userDao.getUserSearch(term, LIMIT);
	}
	
	public void addAdminRole(User user){
		userDao.addAdminRole(user);
	}

}